<template>
  <div>
    <el-dialog
      v-loading.lock="loading"
      class="base-dialog system-user-dialog"
      :custom-class="'panna-dialog_big'"
      :append-to-body="true"
      :title="dataList.AddDeviceBorrow"
      align="center"
      :visible.sync="dialogFormEditVisible"
      @closed="cancel"
    >
      <div>
        <el-form
          ref="formData"
          :model="formData"
          :rules="formDataRules"
          status-icon
          label-width="160px"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item
                :label="dataList.DeviceBorrowType"
                prop="type"
                :error="errorMsg.type"
              >
                <DicDropDownList
                  v-model="formData.type"
                  :dict-code="'borrowType'"
                  @input="dicDropDownListChange"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="dataList.DeviceBorrower"
                prop="borrowPersonId"
                :error="errorMsg.borrowPersonId"
              >
                <UserDropDownList
                  v-if="!type"
                  :value="formData.borrowPersonId"
                  @input="borrowPersonChange"
                />
                <customer-list
                  v-else
                  :value="formData.borrowPersonId"
                  @input="customerChange"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                :label="dataList.DeviceBorrowTime"
                prop="borrowTime"
                :error="errorMsg.borrowTime"
              >
                <el-date-picker
                  v-model="formData.borrowTime"
                  type="date"
                  :placeholder="dataList.SelectDateTime"
                  value-format="yyyy-MM-dd"
                  :picker-options="pickerOptions"
                  @change="borrowTimeChange"
                ></el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="dataList.DeviceBorrowReturnTime"
                prop="returnDate"
                :error="errorMsg.returnDate"
              >
                <el-date-picker
                  v-model="formData.returnDate"
                  type="date"
                  :placeholder="dataList.SelectDateTime"
                  value-format="yyyy-MM-dd"
                  :picker-options="returnDateOptions"
                ></el-date-picker>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item
                :label="dataList.ReasonsOfBorrow"
                prop="reason"
                :error="errorMsg.reason"
              >
                <el-input
                  v-model="formData.reason"
                  autocomplete="off"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item
                :label="dataList.Deviceremark"
                :error="errorMsg.remark"
              >
                <el-input v-model="formData.remark" type="textarea"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <div>
        <el-divider class="el-divider-specail" content-position="left"
          ><span>{{ dataList.BorrowOfDevice }}</span>
          <el-button
            type="primary"
            style="margin-left: 20px"
            @click="choiceDevice"
            >{{ dataList.SelectDevice }}</el-button
          >
        </el-divider>
        <el-table
          :data="list"
          element-loading-text="Loading"
          fit
          highlight-current-row
        >
          >
          <el-table-column :label="dataList.DeviceNumber">
            <template slot-scope="scope">
              {{ scope.row.num }}
            </template>
          </el-table-column>
          <el-table-column
            :label="
              $i18n.locale === 'en' ? dataList.DeviceEName : dataList.DeviceName
            "
          >
            <template slot-scope="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.DeviceSpecifications">
            <template slot-scope="scope">
              {{ scope.row.specifications }}
            </template>
          </el-table-column>

          <el-table-column :label="dataList.DeviceClassifyId">
            <template slot-scope="scope">
              {{ scope.row.classifyName }}
            </template>
          </el-table-column>

          <el-table-column :label="dataList.DeviceSupplierName">
            <template slot-scope="scope">
              {{ scope.row.supplierName }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.DeviceFactoryNum">
            <template slot-scope="scope">
              {{ scope.row.factoryNum }}
            </template>
          </el-table-column>

          <el-table-column :label="dataList.DeviceStatus">
            <template slot-scope="scope">
              {{ scope.row.statusName }}
            </template>
          </el-table-column>
          <el-table-column
            :label="
              $i18n.locale === 'en'
                ? dataList.eDeviceStorageAddress
                : dataList.DeviceStorageAddress
            "
          >
            <template slot-scope="scope">
              {{ scope.row.storageAddress }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.DevicePersonResponsibleId">
            <template slot-scope="scope">
              {{ scope.row.personResponsibleName }}
            </template>
          </el-table-column>
          <el-table-column :label="dataList.Operation">
            <template slot-scope="scope">
              <div class="base-table-operation">
                <el-link
                  size="mini"
                  type="danger"
                  @click="handleDelete(scope.$index)"
                  >{{ btn.Delete }}</el-link
                >
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>

      <div slot="footer" class="dialog-footer" align="center">
        <el-button type="primary" @click="onSubmit('formData')">{{
          btn.Save
        }}</el-button>
        <el-button
          type="primary"
          style="width: 100px"
          @click="onSaveAndSubmit('formData')"
          >{{ btn.SaveAndSubmit }}</el-button
        >
        <el-button @click="cancel">{{ btn.Cancel }}</el-button>
      </div>
      <DeviceDialogList
        v-if="choiceDeviceVisible"
        :dialog-form-visible.sync="choiceDeviceVisible"
        :display-text="displayText"
        :device-id-list="deviceIdList"
        :checked-rows="checkedRows"
        @checkedRowsFun="closeChoiceDevice"
      />
    </el-dialog>
  </div>
</template>

<script>
import {
  create,
  update,
  get,
  createAndVerifyStart,
  updateAndVerifyStart,
} from "../../api/DeviceBorrow.js";
import DeviceDialogList from "../../components/DeviceDialogList.vue";
import DicDropDownList from "../../components/DicDropDownList.vue";
import UserDropDownList from "../../components/UserDropDownList.vue";
import CustomerList from "../../components/CustomerList.vue";

import { waibu, neibu } from "../../utils/const";
export default {
  name: "DeviceBorrowAddDialog",
  components: {
    DeviceDialogList,
    DicDropDownList,
    UserDropDownList,
    CustomerList,
  },
  props: {
    dialogFormEditVisible: {
      type: Boolean,
      default: false,
    },
    editState: {
      type: Boolean,
      default: false,
    },
    id: {
      type: String,
      default: "0",
    },
  },
  data() {
    return {
      checkedRows: [],
      deviceIdList: [],
      displayText: [
        this.$t("ModuleDevice.Device.Normal"),
        this.$t("ModuleDevice.Device.Downgrading"),
      ],
      choiceDeviceVisible: false,
      loading: false,
      innerDialogFormVisible: false,
      list: [],
      type: false, // false 查询用户，true客户
      pagination: {
        pageIndex: 1,
        pageSize: 10,
        total: 0,
      },
      initData: {
        id: 0,
        num: "",
        type: 0,
        typeName: "",
        statusId: 0,
        statusName: "",
        reason: "",
        returnDate: null,
        borrowPersonId: "",
        borrowPersonName: "",
        creatorId: 0,
        creatorName: "",
        remark: "",
      },
      formData: {
        borrowTime: null,
        id: 0,
        num: "",
        type: 0,
        typeName: "",
        statusId: 0,
        statusName: "",
        reason: "",
        returnDate: null,
        borrowPersonId: this.$store.getters.currentUserId,
        borrowPersonName: "",
        creatorId: 0,
        creatorName: "",
        remark: "",
        deviceParts: [],
      },
      returnDateOptions: {
        // 限制日期
        disabledDate: (time) => {
          return time.getTime() < new Date(this.formData.borrowTime).getTime();
        },
      },
      pickerOptions: {
        // 限制日期
        disabledDate(time) {
          return time.getTime() < Date.now() - 3600 * 1000 * 24;
        },
      },
      formDataRules: {
        borrowTime: [
          {
            required: true,
            message: this.$t("ModuleDevice.Message.EntryIntoForceTime"),
            trigger: "change",
          },
          // { validator: validateDate, trigger: "change" },
        ],
        returnDate: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        num: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        type: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        typeName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        statusId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        statusName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        reason: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        borrowPersonId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        borrowPersonName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        creatorId: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunctionPositiveNumber,
          },
        ],
        creatorName: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
        remark: [
          {
            required: true,
            trigger: "blur",
            validator: this.Helper.validateFunction,
          },
        ],
      },
      initErrorMsg: {
        num: "",
        type: "",
        typeName: "",
        statusId: "",
        statusName: "",
        reason: "",
        returnDate: "",
        borrowPersonId: "",
        borrowPersonName: "",
        creatorId: "",
        creatorName: "",
        remark: "",
      },
      errorMsg: {
        num: "",
        type: "",
        typeName: "",
        statusId: "",
        statusName: "",
        reason: "",
        returnDate: "",
        borrowPersonId: "",
        borrowPersonName: "",
        creatorId: "",
        creatorName: "",
        remark: "",
      },
    };
  },
  computed: {
    btn() {
      return this.$t("ModuleDevice.buttons");
    },
    dataList() {
      return this.$t("ModuleDevice.Device");
    },
  },
  watch: {},

  created() {
    this.getBorrowBorrowDeviceIdList();
    if (this.editState) {
      // 编辑
      this.get();
    } else {
      this.formData.type = neibu;
    }
  },
  methods: {
    handleInputBlur(row) {
      // 正则表达式：必须为正整数
      const reg = /^[1-9]\d*$/;
      if (!reg.test(row.loanCount)) {
        this.$message.error(this.$t("ModuleDevice.Message.RegPositiveinteger"));
        row.loanCount = 1; // 重置为默认值
      }
    },
    getBorrowBorrowDeviceIdList() {
      // getBorrowBorrowDeviceIdList().then(res => {
      //   this.deviceIdList = res.data;
      // })
    },
    customerChange(val) {
      this.formData.borrowPersonId = val;
    },
    borrowPersonChange(val) {
      this.formData.borrowPersonId = val;
    },
    // 借用时间改变
    borrowTimeChange(val) {},
    dicDropDownListChange(val) {
      if (val === neibu) {
        this.type = false;
        this.formData.borrowPersonId = this.$store.getters.currentUserId;
      } else if (val === waibu) {
        this.type = true;
        this.formData.borrowPersonId = "";
      }
    },
    handleDelete(index) {
      this.list.splice(index, 1);
    },
    // 关闭选择设备弹框
    closeChoiceDevice(data) {
      this.list = data;
      // var datas = this.list
      //   .map((item) => {
      //     return item.deviceParts;
      //   })
      //   .flat();
      // for (let i = 0; i < datas.length; i++) {
      //   datas[i].loanCount = datas[i].count;
      // }
      // this.formData.deviceParts = datas;
    },
    // 选择设备
    choiceDevice() {
      this.checkedRows = this.list;
      this.choiceDeviceVisible = true;
    },
    cancel() {
      this.$emit("update:dialogFormEditVisible", false);
    },
    get() {
      get({ id: this.id })
        .then((res) => {
          this.formData = res.data;
          this.list = this.formData.deviceBorrowInfoDtoList;
          if (this.formData.type === neibu) {
            this.type = false;
          } else if (this.formData.type === waibu) {
            this.type = true;
          }
        })
        .catch((res) => {});
    },
    closeDialog() {
      this.$parent.getList();
      this.cancel();
    },
    onSubmit() {
      if (
        this.formData.deviceParts !== undefined &&
        this.formData.deviceParts !== null &&
        this.formData.deviceParts.length !== 0
      ) {
        for (let i = 0; i < this.formData.deviceParts.length; i++) {
          if (!this.formData.deviceParts[i].loanCount) {
            this.$message.error(
              this.$t("ModuleDevice.Message.BorrowNumberNotZero")
            );
            this.loading = false;
            return false;
          }
          this.formData.deviceParts[i].partsId =
            this.formData.deviceParts[i].id;
          this.formData.deviceParts[i].id = 0;
        }
      }
      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          // 处理数据
          this.formData.deviceBorrowInfoList = [];
          for (var i = 0; i < this.list.length; i++) {
            var obj = {};
            obj.deviceId = this.list[i].id;
            this.formData.deviceBorrowInfoList.push(obj);
          }
          if (this.formData.id <= 0) {
            create(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            update(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    onSaveAndSubmit() {
      if (this.list === null || this.list.length === 0) {
        this.$message.warning(this.$t("ModuleDevice.Message.TableDataNull"));
        return false;
      }

      if (
        this.formData.deviceParts !== undefined &&
        this.formData.deviceParts !== null &&
        this.formData.deviceParts.length !== 0
      ) {
        for (let i = 0; i < this.formData.deviceParts.length; i++) {
          if (!this.formData.deviceParts[i].loanCount) {
            this.$message.error(
              this.$t("ModuleDevice.Message.BorrowNumberNotZero")
            );
            this.loading = false;
            return false;
          }
          this.formData.deviceParts[i].id = 0;
          this.formData.deviceParts[i].partsId =
            this.formData.deviceParts[i].id;
        }
      }

      this.$refs.formData.validate((valid) => {
        if (valid) {
          this.loading = true;
          this.errorMsg = this.Helper.deepCopy(this.initErrorMsg);
          // 处理数据
          this.formData.deviceBorrowInfoList = [];
          for (var i = 0; i < this.list.length; i++) {
            var obj = {};
            obj.deviceId = this.list[i].id;
            this.formData.deviceBorrowInfoList.push(obj);
          }
          if (this.formData.id <= 0) {
            createAndVerifyStart(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          } else {
            updateAndVerifyStart(this.formData)
              .then((res) => {
                if (res.code === 200) {
                  this.closeDialog();
                } else {
                  this.showValidateMsgCheck(res);
                }
                this.loading = false;
              })
              .catch(() => {
                this.loading = false;
              });
          }
        } else {
          return false;
        }
      });
    },
    showValidateMsgCheck(res) {
      if (res.msg) {
        this.Helper.showValidateMsg("num", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("type", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("typeName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("statusId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("statusName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("reason", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("returnDate", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("borrowPersonId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("borrowPersonName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("creatorId", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("creatorName", this.errorMsg, res.msg);
        this.Helper.showValidateMsg("remark", this.errorMsg, res.msg);
      }
    },
  },
};
</script>
